package com.cmit.upay.monitor.service.impl;

import com.cmit.upay.monitor.util.DateUtils;
import com.cmit.upay.monitor.vo.QueueVO;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 负责将数据写到文件
 */
//@Service
@Slf4j
public class WriteDataToTxtService extends AbstractWriteDataToFileService {
    private BufferedWriter fileWriter;

    public WriteDataToTxtService(String dir, int pageSize) {
        super(dir, pageSize);
    }

    @Override
    protected void write(QueueVO data) {
        try {
            this.fileWriter.write(data.toString());
            if (log.isDebugEnabled()) {
                log.debug("写入数据{}完成", data);
            }
        } catch (IOException e) {
            log.error("写入数据{}出错{}", data, e.getMessage());
        }
    }

    @Override
    public void createNewFile() {
        this.filename = DateUtils.get_yyyyMMddhhmmss();
        this.filename += ".txt";
        try {
            // 如果需要，创建目录
            Files.createDirectories(Paths.get(dir));
            Path path = Paths.get(dir).resolve(this.filename);
            closeWriterIfNecessary();
            // 创建新文件
            this.fileWriter = new BufferedWriter(new FileWriter(path.toAbsolutePath().toString()));
            // 计数重置
            resetFileLines();
            log.info("创建新文件{}完成", this.filename);
        } catch (Exception e) {
            String errorMsg = String.format("创新新文件{}过程出错", this.filename);
            log.error(errorMsg);
            throw new RuntimeException(errorMsg, e);
        }
    }

    @Override
    public void flushData() {
        try {
            fileWriter.flush();
        } catch (Exception e) {
            log.warn("刷新数据出错" + e.getMessage());
        }
    }

    private void closeWriterIfNecessary() {
        if (this.fileWriter != null) {
            try {
                this.fileWriter.close();
            } catch (IOException e) {
                fileWriter = null;
            }
        }
    }
}
